<!-- 海报弹窗 -->
<template>
  <su-popup :show="show" round="10" @close="onClosePoster" type="center" class="popup-box">
    <view class="ss-flex-col ss-col-center ss-row-center">
      <view v-if="!painterImageUrl && !showFallbackCard" class="loading-poster">
        <uni-icons type="spinner-cycle" size="30" color="#999"></uni-icons>
        <text class="loading-text">海报生成中...</text>
      </view>
      
      <!-- 渲染备用卡片方案 -->
      <view v-else-if="showFallbackCard && posterType === 'ecard'" class="fallback-card" 
        :style="{width: posterWidth + 'px', height: posterHeight + 'px'}">
        <view class="fallback-card-inner">
          <!-- 头像 -->
          <view class="fallback-avatar"></view>
          <!-- 内容区 -->
          <view class="fallback-content">
            <view class="fallback-name">{{ cardInfo.title || '姓名' }}</view>
            <view class="fallback-position" v-if="cardInfo.position">{{ cardInfo.position }}</view>
            <view class="fallback-company" v-if="cardInfo.company">{{ cardInfo.company }}</view>
            <view class="fallback-phone" v-if="cardInfo.phone">电话：{{ cardInfo.phone }}</view>
          </view>
        </view>
        
        <!-- 操作提示 -->
        <view class="fallback-tip">
          <uni-icons type="info" size="14" color="#999"></uni-icons>
          <text>长按图片可保存</text>
        </view>
      </view>
      
      <!-- 标准Canvas生成的图片 -->
      <image
        v-else
        class="poster-img"
        :class="{'ecard-poster': posterType === 'ecard'}"
        :src="painterImageUrl"
        :style="{
          width: posterType === 'ecard' ? 'calc(100vw - 60px)' : poster.css.width + 'px',
          height: 'auto',
          aspectRatio: posterType === 'ecard' ? '16/9' : poster.css.width / poster.css.height,
          maxWidth: posterType === 'ecard' ? 'calc(100vw - 60px)' : '90vw',
          maxHeight: posterType === 'ecard' ? '60vh' : '80vh'
        }"
        :show-menu-by-longpress="true"
        @error="handleImageError"
        @load="handleImageLoad"
      />
    </view>
    <view
      class="poster-btn-box ss-m-t-20 ss-flex ss-row-between ss-col-center"
      v-if="!!painterImageUrl || showFallbackCard"
    >
      <button class="cancel-btn ss-reset-button" @tap="onClosePoster">取消</button>
      <button class="save-btn ss-reset-button ui-BG-Main" @tap="onSavePoster">
        {{
          ['wechatOfficialAccount', 'H5'].includes(sheep.$platform.name)
            ? '长按图片保存'
            : '保存图片'
        }}
      </button>
    </view>
    <!--  海报画板：默认隐藏只用来生成海报。生成方式为主动调用  -->
    <l-painter
      isCanvasToTempFilePath
      pathType="url"
      @success="setPainterImageUrl"
      @fail="handlePainterFail"
      @progress="handleProgress"
      @done="handleDone"
      hidden
      ref="painterRef"
      :willReadFrequently="true"
      :canvas-options="{willReadFrequently: true}"
      :sleep="100"
      :afterDelay="300"
      :beforeDelay="200"
      hidpi
    />
  </su-popup>
</template>

<script setup>
  /**
   * 海报生成和展示
   * 提示：小程序码默认跳转首页，由首页进行 spm 参数解析后跳转到对应的分享页面
   * @description 用于生成分享海报，如：分享商品海报。
   * @tutorial https://ext.dcloud.net.cn/plugin?id=2389
   * @property {Boolean} show   弹出层控制
   * @property {Object}  shareInfo 分享信息
   */
  import { reactive, ref, unref, onMounted, watch } from 'vue';
  import sheep from '@/sheep';
  import { getPosterData } from '@/sheep/components/s-share-modal/canvas-poster/poster';

  const props = defineProps({
    show: {
      type: Boolean,
      default: false,
    },
    shareInfo: {
      type: Object,
      default: () => {
      },
    },
  });

  // 监听show属性，当显示弹窗时自动开始生成海报
  watch(() => props.show, (newVal) => {
    if (newVal) {
      console.log('弹窗显示，自动开始生成海报');
      setTimeout(() => {
        getPoster();
      }, 100);
    }
  });

  const poster = reactive({
    css: {
      // 根节点若无尺寸，自动获取父级节点
      width: sheep.$platform.device.windowWidth * 0.9,
      height: 600,
    },
    views: [],
  });

  // 新增变量用于电子名片海报
  const posterType = ref('');
  const posterWidth = ref(0);
  const posterHeight = ref(0);
  const retryCount = ref(0);
  const maxRetries = 3;
  const imageLoaded = ref(false);
  const showFallbackCard = ref(false); // 是否显示备用卡片
  const cardInfo = ref({}); // 卡片信息

  const emits = defineEmits(['success', 'close']);

  const onClosePoster = () => {
    painterImageUrl.value = '';
    retryCount.value = 0;
    imageLoaded.value = false;
    showFallbackCard.value = false;
    emits('close');
  };

  const painterRef = ref(); // 海报画板
  const painterImageUrl = ref(''); // 海报 url
  
  // 渲染海报
  const renderPoster = async () => {
    try {
      console.log('开始渲染海报...');
      await painterRef.value.render(unref(poster));
      console.log('渲染海报完成');
    } catch(error) {
      console.error('渲染海报失败:', error);
      handlePainterFail(error);
    }
  };
  
  // 获得生成的图片
  const setPainterImageUrl = (path) => {
    console.log('获取到海报图片URL:', path);
    painterImageUrl.value = path;
  };
  
  // 处理生成失败
  const handlePainterFail = (error) => {
    console.error('海报生成失败:', error);
    if (retryCount.value < maxRetries) {
      console.log(`尝试重新渲染 (${retryCount.value + 1}/${maxRetries})...`);
      retryCount.value++;
      setTimeout(() => renderPoster(), 800); // 延迟更长时间后重试
    } else {
      console.log('尝试次数已达最大值，启用备用卡片方案');
      // 如果是电子名片类型，启用备用卡片
      if (posterType.value === 'ecard') {
        // 启用备用卡片方案
        showFallbackCard.value = true;
      } else {
        sheep.$helper.toast('海报生成失败，请重试');
      }
    }
  };
  
  // 处理进度更新
  const handleProgress = (progress) => {
    console.log(`海报渲染进度: ${progress * 100}%`);
  };
  
  // 渲染完成
  const handleDone = () => {
    console.log('海报绘制完成，正在生成图片...');
  };
  
  // 图片加载失败处理
  const handleImageError = (e) => {
    console.error('图片加载失败:', e);
    if (retryCount.value < maxRetries) {
      console.log(`图片加载失败，尝试重新渲染 (${retryCount.value + 1}/${maxRetries})...`);
      retryCount.value++;
      setTimeout(() => renderPoster(), 800);
    } else {
      console.log('图片加载失败尝试次数已达最大值，启用备用卡片方案');
      // 如果是电子名片类型，启用备用卡片
      if (posterType.value === 'ecard') {
        // 启用备用卡片方案
        showFallbackCard.value = true;
      } else {
        sheep.$helper.toast('海报图片加载失败');
      }
    }
  };
  
  // 图片加载成功
  const handleImageLoad = () => {
    console.log('海报图片加载成功');
    imageLoaded.value = true;
  };
  
  // 保存海报图片
  const onSavePoster = () => {
    if (showFallbackCard.value) {
      // 使用备用卡片时
      sheep.$helper.toast('请长按图片保存');
      return;
    }
    
    if (!imageLoaded.value) {
      sheep.$helper.toast('图片还未完全加载，请稍候');
      return;
    }
    
    if (['WechatOfficialAccount', 'H5'].includes(sheep.$platform.name)) {
      sheep.$helper.toast('请长按图片保存');
      return;
    }

    // 非H5 保存到相册
    uni.saveImageToPhotosAlbum({
      filePath: painterImageUrl.value,
      success: (res) => {
        onClosePoster();
        sheep.$helper.toast('保存成功');
      },
      fail: (err) => {
        sheep.$helper.toast('保存失败');
        console.log('图片保存失败:', err);
      },
    });
  };

  // 状态检查方法，用于超时后的自动恢复
  const checkPosterStatus = () => {
    console.log('检查海报状态...');
    // 如果还在加载状态，且已经超过了一定时间，直接显示备用卡片
    if (!painterImageUrl.value && !showFallbackCard.value && posterType.value === 'ecard') {
      console.log('海报生成超时，启用备用卡片');
      showFallbackCard.value = true;
    }
  };

  // 手动创建img元素验证URL
  const checkImageUrl = (url) => {
    return new Promise((resolve) => {
      // #ifdef H5
      const img = new Image();
      img.onload = () => resolve(true);
      img.onerror = () => resolve(false);
      img.src = url;
      // #endif
      
      // #ifndef H5
      resolve(true); // 非H5环境暂时不做检查
      // #endif
    });
  };

  // 提取卡片信息
  const extractCardInfo = () => {
    if (props.shareInfo?.poster?.type === 'ecard') {
      // 复制poster中所有属性到cardInfo中
      const poster = props.shareInfo.poster || {};
      cardInfo.value = { ...poster };
      
      // 添加默认宽高，以确保布局正确
      if (!cardInfo.value.width) {
        cardInfo.value.width = sheep.$platform.device.windowWidth * 0.9;
      }
      if (!cardInfo.value.height) {
        cardInfo.value.height = cardInfo.value.width * 0.56;
      }
      
      // 确保关键字段都存在
      const sourceData = props.shareInfo.params || {};
      if (!cardInfo.value.title && sourceData.title) {
        cardInfo.value.title = sourceData.title;
      }
      if (!cardInfo.value.image && sourceData.image) {
        cardInfo.value.image = sourceData.image;
      }
      
      // 映射可能的不同字段名
      if (sourceData.name && !cardInfo.value.name) {
        cardInfo.value.name = sourceData.name;
      }
      if (cardInfo.value.title && !cardInfo.value.name) {
        cardInfo.value.name = cardInfo.value.title;
      }
      if (sourceData.avatar && !cardInfo.value.avatar) {
        cardInfo.value.avatar = sourceData.avatar;
      }
      if (cardInfo.value.image && !cardInfo.value.avatar) {
        cardInfo.value.avatar = cardInfo.value.image;
      }
      
      console.log('提取的名片信息:', cardInfo.value);
      return true;
    }
    return false;
  };

  // 获得海报数据
  const getPoster = async () => {
    try {
      // 重置状态
      painterImageUrl.value = '';
      retryCount.value = 0;
      imageLoaded.value = false;
      showFallbackCard.value = false;
      
      console.log('获取海报配置...');
      
      // 检查是否是电子名片并且有预生成图片
      if (props.shareInfo?.poster?.imageOnly && props.shareInfo?.poster?.imageUrl) {
        console.log('使用预生成的海报图片:', props.shareInfo.poster.imageUrl);
        painterImageUrl.value = props.shareInfo.poster.imageUrl;
        imageLoaded.value = true;
        return;
      }
      
      // 提取卡片信息
      const isECard = extractCardInfo();
      
      // 设置海报类型
      posterType.value = props.shareInfo?.poster?.type || '';
      
      // 设置电子名片海报尺寸
      if (isECard) {
        posterWidth.value = cardInfo.value.width;
        posterHeight.value = cardInfo.value.height;
      }
      
      // 根据海报类型获取海报配置
      let posterConfig;
      
      try {
        if (posterType.value === 'ecard') {
          // 电子名片类型特殊处理
          console.log('获取电子名片海报配置...');
          
          // 检查是否有完整的模板数据
          if (props.shareInfo?.poster?.templateData) {
            console.log('使用完整模板数据生成海报');
            
            // 完整传递所有必要数据
            posterConfig = await getPosterData({
              width: posterWidth.value,
              height: posterHeight.value,
              shareInfo: props.shareInfo
            });
          } else {
            console.log('使用基础信息生成海报');
            posterConfig = await getPosterData({
              width: posterWidth.value,
              height: posterHeight.value,
              shareInfo: {
                ...props.shareInfo,
                poster: {
                  ...props.shareInfo.poster,
                  posterData: cardInfo.value // 兼容旧版实现
                }
              }
            });
          }
        } else {
          // 其他类型海报处理
          posterConfig = await getPosterData({
            width: sheep.$platform.device.windowWidth * 0.9,
            shareInfo: props.shareInfo,
          });
        }
        
        console.log('获取到海报配置:', posterConfig);
        
        // 设置海报数据
        poster.css = posterConfig.css;
        poster.views = posterConfig.views;
        
        // #ifdef H5
        // 在H5环境下，如果是电子名片类型，设置超时检查
        if (posterType.value === 'ecard' && sheep.$platform.name === 'H5') {
          setTimeout(() => checkPosterStatus(), 8000);
        }
        // #endif
        
        console.log('正在调用渲染...');
        // 确保组件已加载完成后再渲染
        setTimeout(() => renderPoster(), 500);
        
        return posterConfig;
      } catch (error) {
        console.error('获取海报配置失败:', error);
        throw error;
      }
    } catch (error) {
      console.error('获取海报数据失败:', error);
      sheep.$helper.toast('海报生成失败');
      
      // 如果是电子名片，尝试使用备用卡片
      if (posterType.value === 'ecard') {
        showFallbackCard.value = true;
      }
      return null;
    }
  };

  defineExpose({
    getPoster,
    checkPosterStatus
  });
</script>

<style lang="scss" scoped>
  .popup-box {
    position: relative;
    padding: 30rpx;
  }
  
  .loading-poster {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40rpx;
    
    .loading-text {
      margin-top: 20rpx;
      font-size: 28rpx;
      color: #999;
    }
  }

  .poster-title {
    color: #999;
  }
  
  /* 备用卡片样式 */
  .fallback-card {
    margin: 0 auto;
    position: relative;
    background-color: #FFFFFF;
    border-radius: 16rpx;
    box-shadow: 0 8rpx 24rpx rgba(0,0,0,0.15);
    border: 1rpx solid #eee;
    overflow: hidden;
    
    .fallback-card-inner {
      width: 100%;
      height: 100%;
      position: relative;
      padding: 40rpx;
      box-sizing: border-box;
    }
    
    .fallback-avatar {
      position: absolute;
      width: 20%;
      height: 0;
      padding-bottom: 20%;
      left: 5%;
      top: 10%;
      border-radius: 50%;
      background-color: #f2f2f2;
    }
    
    .fallback-content {
      padding-left: 30%;
      padding-top: 10%;
      text-align: left;
      
      .fallback-name {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 15rpx;
      }
      
      .fallback-position {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .fallback-company {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .fallback-phone {
        font-size: 28rpx;
        color: #666;
        position: absolute;
        bottom: 40rpx;
        left: 40rpx;
      }
    }
    
    .fallback-tip {
      position: absolute;
      right: 20rpx;
      bottom: -40rpx;
      display: flex;
      align-items: center;
      
      text {
        font-size: 24rpx;
        color: #999;
        margin-left: 6rpx;
      }
    }
  }

  // 分享海报
  .poster-btn-box {
    width: 600rpx;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: -80rpx;

    .cancel-btn {
      width: 240rpx;
      height: 70rpx;
      line-height: 70rpx;
      background: $white;
      border-radius: 35rpx;
      font-size: 28rpx;
      font-weight: 500;
      color: $dark-9;
    }

    .save-btn {
      width: 240rpx;
      height: 70rpx;
      line-height: 70rpx;
      border-radius: 35rpx;
      font-size: 28rpx;
      font-weight: 500;
    }
  }

  .poster-img {
    border-radius: 20rpx;
    margin: 0 auto;
    display: block;
    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
    object-fit: contain; // 保持图片比例
    max-width: 90vw; // 最大宽度
    max-height: 80vh; // 最大高度
    
    &.ecard-poster {
      margin: 30rpx auto;
      border-radius: 20rpx;
      box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
      border: 1rpx solid #f2f2f2;
      object-fit: contain; // 保持图片比例
    }
  }
</style>
